import { Add } from "@material-ui/icons";
import { Typography } from "@mui/material";
import { ChangeEventHandler, FC, ReactElement, memo } from "react";
import styled from "styled-components";

interface IProps {
  onSelect: (file: string) => void;
}

const AddCustomerCover: FC<IProps> = ({ onSelect }): ReactElement => {
  const selectImage: ChangeEventHandler<HTMLInputElement> = e => {
    const files = e.target.files;
    if (!files) return;
    const reader = new FileReader();
    reader.onload = () => {
      const result = reader.result as string;
      onSelect(result);
      //@ts-ignore
      e.target.value = null; //将value重置防止下次还选这张不触发change事件
    };
    reader.readAsDataURL(files[0]);
  };

  return (
    <Container>
      <input onChange={selectImage} type='file' />
      <Add />
      <Typography>上传</Typography>
    </Container>
  );
};

export default memo(AddCustomerCover);

const Container = styled.div`
  position: relative;
  width: 7rem;
  height: 7rem;
  border-radius: 0.5rem;
  box-shadow: 0 0 8px 0 #ccc;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  color: #ccc;
  margin: 0.5rem;

  input {
    cursor: pointer;
    opacity: 0;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
  }
`;
